from datetime import datetime
from sqlalchemy import orm, Column, Integer, DateTime
from flask_sqlalchemy import SQLAlchemy, Model, SignallingSession, get_state


class RoutingSession(SignallingSession):
    def get_bind(self, mapper=None, clause=None):
        state = get_state(self.app)
        if self._flushing:
            return state.db.get_engine(self.app, bind='master')
        else:
            return state.db.get_engine(self.app, bind='master')


class RoutingSQLAlchemy(SQLAlchemy):
    """数据库读写分离"""
    def create_session(self, options):
        return orm.sessionmaker(class_=RoutingSession, db=self, **options)


class BaseModel(Model):
    __table_args = {'mysql_charset': 'utf8mb4'}
    id = Column(Integer, primary_key=True)
    #gmtCreated = Column(DateTime, default=datetime.now)
    #gmtModify = Column(DateTime, default=datetime.now, onupdate=datetime.now)

    def to_dict(self):
        columns = self.__table__.columns.keys()
        return {key: getattr(self, key) for key in columns}


db = RoutingSQLAlchemy(model_class=BaseModel)
